package pl.asoft.nbp.util;

import org.apache.log4j.Logger;
import pl.asoft.nbp.service.NbpService;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
 * Created by rbiedrawa on 2014-12-01.
 */
public class LinkCreator {
	private static final Logger LOG = Logger.getLogger(LinkCreator.class);
	private static final int MYTHREADS = 10;

	private final List<String> days;
	private final List<String> list;
	
	private final List<String> listOfValidLinks = Collections
			.synchronizedList(new ArrayList<>());

	public LinkCreator(List<String> days, List<String> list) {
		this.days = Collections.synchronizedList(days);
		this.list = Collections.synchronizedList(list);
	}

	public void start() {
		ExecutorService executor = Executors.newFixedThreadPool(MYTHREADS);

        for (String line : list) {
            Runnable worker = new LinkCreatorTask(line, days);
            executor.execute(worker);
        }
		executor.shutdown();
		// we want to wait until all threads are finish, and later we will get
		// the data that we collected
		while (!executor.isTerminated()) {
		}

		LOG.debug("NBP valid links: " + listOfValidLinks.size());
	}

	private class LinkCreatorTask implements Runnable {

		private final String line;
		private final List<String> days;

		public LinkCreatorTask(String line, List<String> days) {
			this.line = line;
			this.days = days;
		}

		@Override
		public void run() {
            days.parallelStream().filter(d -> line.endsWith(d)).forEach(d ->
                    listOfValidLinks.add(NbpService.URL + line + NbpService.URL_SUFFIX));
		}
	}

	public List<String> getListOfValidLinks() {
		return listOfValidLinks;
	}
	
}
